package com.example.homework8.fragment;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.example.homework8.R;
import com.example.homework8.adapter.MoneyAdapter;
import com.example.homework8.bean.MoneyInfo;
import com.example.homework8.database.MoneyDBHelper;
import com.example.homework8.database.RecordDBHelper;
import com.example.homework8.utils.SharedUtil;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static android.content.ContentValues.TAG;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link MoneyFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MoneyFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public MoneyFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment MoneyFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static MoneyFragment newInstance(String param1, String param2) {
        MoneyFragment fragment = new MoneyFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }
    ArrayList<MoneyInfo> moneyInfos;
    MoneyAdapter moneyAdapter;
    TextView remain,input,output;
    ListView listView;
    Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            if(msg.what ==1 ){
                Log.d(TAG, "handleMessage: remove item");
                MoneyDBHelper recordhelper = MoneyDBHelper.getInstance(getActivity(), 1);
                recordhelper.openReadLink();
                int position = (int) msg.obj;
                recordhelper.delete("_id=" + moneyInfos .get((int)position).rowid);
                moneyInfos.remove(position);
                moneyAdapter.notifyDataSetChanged();
                updatesum();
            }
        }
    };
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_money, container, false);
        FloatingActionButton floatingActionButton = view.findViewById(R.id.addmoneylog);
        remain= view.findViewById(R.id.remain);
        input = view.findViewById(R.id.input);
        output = view.findViewById(R.id.output);
        listView = view.findViewById(R.id.moneylist);
        MoneyDBHelper moneyDBHelper = MoneyDBHelper.getInstance(getActivity(),1);
        String uname = SharedUtil.getIntance(getActivity()).readShared("loginuser","未登录");
        SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd hh:mm:ss");
        String  createtime =   ft.format(new Date());

        moneyInfos = moneyDBHelper.query("username = " + uname + " AND createtime like '" + createtime.substring(0, 7) + "%'");
        Log.d(TAG, "onCreateView: money list length" + moneyInfos.size());
        moneyAdapter= new MoneyAdapter(moneyInfos,getActivity(),handler);

        listView.setAdapter(moneyAdapter);
        int remainmoney = 0;
        int input_m = 0;
        int output_m=0;
        for (MoneyInfo moneyInfo: moneyInfos) {
            remainmoney += moneyInfo.current;
            if(moneyInfo.current>0)
                input_m += moneyInfo.current;
            else
                output_m += moneyInfo.current;
        }
        remain.setText(remainmoney+"");
        output.setText(output_m+"");
        input.setText(input_m+"");


        floatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder bb = new AlertDialog.Builder(getActivity());
                View dialog_add_money_log = LayoutInflater.from(getContext()).inflate(R.layout.dialog_add_money_log,null,false);
                bb.setView(dialog_add_money_log);
                EditText current_log = dialog_add_money_log.findViewById(R.id.current_log);
                EditText cate_log = dialog_add_money_log.findViewById(R.id.cate_log);
                RadioButton input_rad = dialog_add_money_log.findViewById(R.id.input_rad);
                RadioButton out_rad = dialog_add_money_log.findViewById(R.id.output_rad);

                bb.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        if(current_log.getText().toString().equals("") ||
                            !isNumeric(current_log.getText().toString()) ||
                            cate_log.getText().toString().equals("") ||
                                (!input_rad.isChecked() && !out_rad.isChecked() )
                        ){
                            Toast.makeText(getActivity(),"请输入金额和分类",Toast.LENGTH_SHORT).show();
                        }else{
                            MoneyInfo moneyInfo = new MoneyInfo();
                            moneyInfo.username = SharedUtil.getIntance(getActivity()).readShared("loginuser","null");
                            int curr = Integer.parseInt(current_log.getText().toString());
                            moneyInfo.current =  input_rad.isChecked()   ? curr:curr * -1;
                            moneyInfo.cate = cate_log.getText().toString();
                            MoneyDBHelper.getInstance(getActivity(),1).insert(moneyInfo);
                            moneyInfos.add(moneyInfo);
                            moneyAdapter.notifyDataSetChanged();
                            updatesum();
                            dialogInterface.dismiss();
                        }
                    }
                });
                bb.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                });
                bb.setMessage("是否删除记录");
                bb.setTitle("提示");
                bb.show();
            }
        });
        return view;
    }
    public void updatesum () {
        int remainmoney = 0;
        int input_m = 0;
        int output_m=0;
        for (MoneyInfo moneyInfo: moneyInfos) {
            remainmoney += moneyInfo.current;
            if(moneyInfo.current>0)
                input_m += moneyInfo.current;
            else
                output_m += moneyInfo.current;
        }
        remain.setText(remainmoney+"");
        output.setText(output_m+"");
        input.setText(input_m+"");

    }
    public boolean isNumeric(String str){
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if( !isNum.matches() ){
            return false;
        }
        return true;
    }
}